﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using log4net;
using mshtml;
using Nissen_Common;
using Nissen_Marking.Properties;
using Nissen_Model;
using Nissen_Resources;
using PosHacker;
using Utility_Log;

namespace Nissen_Marking.Forms
{
	
	public partial class FormPCMarking : Form
	{
		public Form vParentForm { get; set; }
		public POSHacker vPOSHacker { get; set; }
		private bool isSubmit = false;

		private bool isFirst = true;
		
		public FormPCMarking(string vLink)
		{
			InitializeComponent();
			this.wbPCMarking.Url = new Uri(vLink);//new Uri(vPOSHacker.GetPCMarkingActionLink());

		}

		private void FormPCMarking_Load(object sender, EventArgs e)
		{
			this.buttonMarkConfirmed.Enabled = false;
			this.ngButton.Enabled = false;
		}

		/// <summary>
		/// WB加载完成
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void wbPCMarking_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
		{
			if (isFirst)
			{
				this.isFirst = false;
				return;
			}

			if (e.Url.ToString() != wbPCMarking.Url.ToString())
				return;
            
			this.PageControl();

			this.buttonMarkConfirmed.Enabled = true;
			this.ngButton.Enabled = true;
		}

		/// <summary>
		/// LOG
		/// </summary>
		private void LogMarkInfo(string submitFlag)
		{

			PartrailQuestionService partrailQuestionService = new PartrailQuestionService();

			List<RecordData> recordDatas = GetSubmitData(submitFlag);

			partrailQuestionService.SubmitMarkableQuestions(recordDatas);

		}

		/// <summary>
		/// 获得提交数据
		/// </summary>
		/// <returns></returns>
		private List<RecordData> GetSubmitData(string submitFlag)
		{
			List<RecordData> recordDatas = new List<RecordData>();

			HtmlElementCollection inputs = wbPCMarking.Document.GetElementsByTagName("input");

			var regNo = wbPCMarking.Document.GetElementById("regNo").GetAttribute("value");
			
			foreach (HtmlElement input in inputs)
			{
				var inputName = input.GetAttribute("name");
				Regex rg = new Regex(@"^markMap");
				Match mc = rg.Match(inputName);
				if (mc.Success)
				{
					var questionNo = "";
					string parrentStr = @"markMap\((\d+)\)";
					Match ma = Regex.Match(inputName, parrentStr, RegexOptions.IgnoreCase);
					if (ma.Success)
					{
						//题号
						questionNo = ma.Groups[1].ToString();
					}
					RecordData recordData = new RecordData();

					var strQuestionNo = regNo
								  + "_"
								  + Nissen_Common.ContextManager.Instance._FormSetCourse.subjectCourseTestId
								  + "_"
								  + questionNo
                                  +"_A";

					recordData.QuestionNo = strQuestionNo;
					if (submitFlag =="ok")
					{
						recordData.QuestionResult = input.GetAttribute("value");
					}
					else if (submitFlag =="ng")
					{
						recordData.QuestionResult = "5";
					}
					recordData.WorkerNo = Nissen_Common.ContextManager.Instance.CurrentUser.LoginSSO;
					recordData.NissenSSO = Nissen_Common.ContextManager.Instance.CurrentUser.NissenSSO.NissenSSOCode;
					recordData.FirstWorkDate = DateTime.Now;
					recordData.EndWorkDate = DateTime.Now;

					recordData.MachineCode = "";
					recordDatas.Add(recordData);
				}

			}
			return recordDatas;

		}
		/// <summary>
		/// 隐藏控件
		/// </summary>
		/// <param name="strOutHtml"></param>
		/// <returns></returns>
		private string DivHidden(string strOutHtml)
		{

			return "<div style=\"visibility:hidden\">" + strOutHtml + "</div>";
		}
		/// <summary>
		/// 画面控制
		/// </summary>
		private void PageControl()
		{

			HTMLDocument mainFrmhtmlDocument = (HTMLDocument)wbPCMarking.Document.Window.Frames["mainFrm"].Document.DomDocument;

			var btnBackToMenu = (HTMLButtonElement)mainFrmhtmlDocument.getElementById("backToMenu");

			if (btnBackToMenu != null)
			{
				btnBackToMenu.outerHTML = this.DivHidden(btnBackToMenu.outerHTML);
			}

			HTMLDocument answerSheetFrmHtmlDocument = (HTMLDocument)wbPCMarking.Document.Window.Frames["answerSheetFrm"].Document.DomDocument;

			var btnOk = (HTMLButtonElement)answerSheetFrmHtmlDocument.getElementById("ok");

			var btnNg = (HTMLButtonElement)answerSheetFrmHtmlDocument.getElementById("ng");

			if (btnOk != null)
			{
				btnOk.outerHTML = this.DivHidden(btnOk.outerHTML);
			}
			if (btnNg != null)
			{
				btnNg.outerHTML = this.DivHidden(btnNg.outerHTML);
			}
			
			//IHTMLDocument2 doc = (IHTMLDocument2)wbPCMarking.Document.DomDocument;

			//foreach (IHTMLElement LV0 in doc.all)
			//{
			//    if (LV0.tagName.ToUpper() == "FRAME")
			//    {
			//        //返回按钮隐藏
			//        IHTMLFrameBase2 LV0_FRAME = (IHTMLFrameBase2)LV0;
			//        if (LV0_FRAME.contentWindow.name == "mainFrm")
			//        {
			//            foreach (IHTMLElement LV2 in LV0_FRAME.contentWindow.document.all)
			//            {
			//                HTMLDocument doc1 = (HTMLDocument)LV2.document;
			//                HTMLButtonElement button = (HTMLButtonElement)doc1.getElementById("backToMenu");
			//                if (button != null)
			//                {
			//                    button.outerHTML = this.DivHidden(button.outerHTML);
			//                }
			//            }
			//        }
			//        //提交按钮隐藏
			//        if (LV0_FRAME.contentWindow.name == "answerSheetFrm")
			//        {
			//            foreach (IHTMLElement LV2 in LV0_FRAME.contentWindow.document.all)
			//            {
			//                HTMLDocument doc1 = (HTMLDocument)LV2.document;
			//                HTMLButtonElement okButton = (HTMLButtonElement)doc1.getElementById("ok");
			//                if (okButton != null)
			//                {
			//                    okButton.outerHTML = this.DivHidden(okButton.outerHTML);
			//                }
			//                HTMLButtonElement ngButton = (HTMLButtonElement)doc1.getElementById("ng");
			//                if (ngButton != null)
			//                {
			//                    ngButton.outerHTML = this.DivHidden(ngButton.outerHTML);
			//                }
							
			//            }
			//        }
			//    }
				
			//}
		}
		/// <summary>
		/// 画面关闭
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void FormPCMarking_FormClosed(object sender, FormClosedEventArgs e)
		{
			vParentForm.Show();
		}
		/// <summary>
		/// 提交
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void buttonMarkConfirmed_Click(object sender, EventArgs e)
		{

			try
			{

				if (this.buttonMarkConfirmed.Enabled == false)
				{
					return;
				}
				this.buttonMarkConfirmed.Enabled = false;
				this.ngButton.Enabled = false;

				submitForm(true);
				
				//HTMLDocument htmlDocument = (HTMLDocument)wbPCMarking.Document.Window.Frames["answerSheetFrm"].Document.DomDocument;

				//var btnOk = (HTMLButtonElement)htmlDocument.getElementById("ok");
				//LogMarkInfo("ok");
				//btnOk.click();//submit
				
			}
			catch (Exception ex)
			{
                //MessageBox.Show(ex.Message);
				MessageBox.Show(ResourceCommon.GetResource("SubmitFail"));
				Log4netManager.Instance.Logs.Error("error", ex);
			}
			
		}

		private void ngButton_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.ngButton.Enabled == false)
				{
					return;
				}
				this.buttonMarkConfirmed.Enabled = false;
				this.ngButton.Enabled = false;

				submitForm(false);

				//HTMLDocument htmlDocument = (HTMLDocument)wbPCMarking.Document.Window.Frames["answerSheetFrm"].Document.DomDocument;

				//var btnOk = (HTMLButtonElement)htmlDocument.getElementById("ng");
				//LogMarkInfo("ng");
				//btnOk.click();//submit

			}
			catch (Exception ex)
			{

				MessageBox.Show(ResourceCommon.GetResource("SubmitFail"));
				Log4netManager.Instance.Logs.Error("error", ex);
			}
		}


		private void submitForm(bool result)
		{
			if (result == true)
			{
				bool existUnmarkedItem =
					(bool) wbPCMarking.Document.Window.Frames["answerSheetFrm"].Document.InvokeScript("existUnmarkedItem");

				if (existUnmarkedItem == true)
				{
					//There are some unmarked question. Save this ?
					if (
						MessageBox.Show(ResourceCommon.GetResource("SubmitPCMarkingConfirm"), "", MessageBoxButtons.OKCancel,
						                MessageBoxIcon.Question) == DialogResult.Cancel)
					{
						this.buttonMarkConfirmed.Enabled = true;
						this.ngButton.Enabled = true;
						return;
					}
				}

				LogMarkInfo("ok");

			}
			else
			{
				//Is it OK to change status to "to be fixed". \nIf OK, please go ahead and call administraor.
				if (
					MessageBox.Show(ResourceCommon.GetResource("AbnormalDataConfirm"), "", MessageBoxButtons.OKCancel,
					                MessageBoxIcon.Question) == DialogResult.Cancel)
				{
					this.buttonMarkConfirmed.Enabled = true;
					this.ngButton.Enabled = true;
					return;
				}
				LogMarkInfo("ng");
				wbPCMarking.Document.GetElementById("isAbnormal").SetAttribute("value", "true");

			}

			wbPCMarking.Document.GetElementById("isSkipped").SetAttribute("value", "false");
			wbPCMarking.Document.GetElementById("testeeId").SetAttribute("value", "");
			wbPCMarking.Document.GetElementById("commentXml").SetAttribute("value", "<canvas/>"); //不确定，是否死值

			HTMLDocument htmlDocument = (HTMLDocument) wbPCMarking.Document.DomDocument;
			HTMLFormElement htmlFormElementClass = (HTMLFormElement)htmlDocument.forms.item("confirmMarkForm");
			htmlFormElementClass.submit();
		}

		private void FormPCMarking_KeyDown(object sender, KeyEventArgs e)
		{
			//if(e.KeyCode == Keys.Space)
			//{
			//    buttonMarkConfirmed_Click(null, null);
			//}

			//this.Focus();
			//this.WindowState = FormWindowState.Maximized;

		}
		bool _isFirstKeyDown = true;
		private void wbPCMarking_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
		{
			if (e.KeyCode == Keys.Space)
			{
				if (_isFirstKeyDown)
				{
					buttonMarkConfirmed_Click(null, null);
					
				}
				_isFirstKeyDown = !_isFirstKeyDown;

			}
		}

	
	}
}
